/**
 * @(#)DingService.java 2017å¹´9æ28æ¥	ä¸å2:43:54 Copyrights (C) 2017é«å¾·ä¿¡æ¯ææ¯æéå¬å¸
 */
package com.wwy.monitor.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.aliwork.mc.model.DTMessageBody;
import com.alibaba.aliwork.mc.model.MessageVO;
import com.alibaba.aliwork.mc.service.AliworkMcService;
import com.alibaba.iwork.shared.commons.model.result.PojoResult;
import com.wwy.monitor.model.constants.McConstants;
import com.wwy.monitor.model.enumeration.DingBodyTypeEnum;
import com.wwy.monitor.model.enumeration.ExceptionCodeEnum;
import com.wwy.monitor.model.vo.DingMessageVO;
import com.wwy.monitor.service.BaseService;
import com.wwy.monitor.util.BeanMapper;
import com.autonavi.dyui.common.exception.BizException;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * (ç±»ååè½è¯´ææè¿°)
 * <p>
 * ä¿®æ¹åå²: <br>
 * ä¿®æ¹æ¥æ ä¿®æ¹äººå çæ¬ ä¿®æ¹åå®¹<br>
 * -------------------------------------------------<br>
 * 2017å¹´9æ28æ¥ ä¸å2:43:54 fulianqiu 1.0 åå§ååå»º<br>
 * </p>
 *
 * @author fulianqiu
 * @version 1.0
 * @since JDK1.7
 */
@Service("dingMcService")
public class DingMcService extends BaseService {
    @Autowired
    public AliworkMcService aliworkMcService;

    public boolean sendMsg(DingMessageVO message) {
//校验参数
        checkParam(message);
// step 1, æå»ºaliwork-mc æ¶æ¯å¯¹è±¡
        MessageVO msg = new MessageVO();
        BeanMapper.copy(message, msg);
// step 2, æå»ºæ¶æ¯å¯¹è±¡
        dealBody(message, msg);
// step 3, åé
        msg.setMsgTypeId(McConstants.DING_MSGTYPEID);
        PojoResult<Boolean> result = aliworkMcService.sendMCMsg(msg);
        logger.info("send Ding result:content={},errorCode={},errorLevel={},errorMsg={},requestId={}",
                result.getContent(), result.getErrorCode(), result.getErrorLevel(),
                result.getErrorMsg(), result.getRequestId());
        if (!String.valueOf(ExceptionCodeEnum.SUCCESS.code()).equals(result.getErrorCode())) {
            throw new BizException(ExceptionCodeEnum.SERVER_ERROR.code(), "send DingDing fail");
        }
        return true;
    }

    private void dealBody(DingMessageVO message, MessageVO msg) {
        if (Strings.isNullOrEmpty(message.getType())) {
            return;
        }
        if (message.getType().equals(DingBodyTypeEnum.OA.getType())) {
            DTMessageBody.OABody oABody = dealOABody(message);
            msg.setdTMessageBody(oABody);
        }
        if (message.getType().equals(DingBodyTypeEnum.TEXT.getType())) {
            DTMessageBody.TextBody textBody = dealTextBody(message);
            msg.setdTMessageBody(textBody);
        }
        if (message.getType().equals(DingBodyTypeEnum.LINK.getType())) {
            DTMessageBody.LinkBody linkBody = dealLinkBody(message);
            msg.setdTMessageBody(linkBody);
        }
        if (message.getType().equals(DingBodyTypeEnum.IMAGE.getType())) {
            DTMessageBody.ImageBody imageBody = dealImageBody(message);
            msg.setdTMessageBody(imageBody);
        }
        if (message.getType().equals(DingBodyTypeEnum.VOICE.getType())) {
            DTMessageBody.VoiceBody voiceBody = dealVoiceBody(message);
            msg.setdTMessageBody(voiceBody);
        }
        if (message.getType().equals(DingBodyTypeEnum.FILE.getType())) {
            DTMessageBody.FileBody fileBody = dealFileBodyBody(message);
            msg.setdTMessageBody(fileBody);
        }
    }

    /**
     * (å¤çfileæ¶æ¯å¯¹è±¡)
     *
     * @param message
     * @return
     */
    private DTMessageBody.FileBody dealFileBodyBody(DingMessageVO message) {
        DTMessageBody.FileBody fileBody = new DTMessageBody.FileBody();
        fileBody.setType(message.getType());
        if (message.getFileBody() != null) {
            fileBody.setMedia_id(message.getFileBody().getMedia_id());
        }
        return fileBody;
    }

    /**
     * (å¤çvoiceæ¶æ¯å¯¹è±¡)
     *
     * @param message
     * @return
     */
    private DTMessageBody.VoiceBody dealVoiceBody(DingMessageVO message) {
        DTMessageBody.VoiceBody voiceBody = new DTMessageBody.VoiceBody();
        voiceBody.setType(message.getType());
        if (message.getVoiceBody() != null) {
            voiceBody.setMedia_id(message.getVoiceBody().getMedia_id());
        }
        return voiceBody;
    }

    /**
     * (å¤çimageæ¶æ¯å¯¹è±¡)
     *
     * @param message
     * @return
     */
    private DTMessageBody.ImageBody dealImageBody(DingMessageVO message) {
        DTMessageBody.ImageBody imageBody = new DTMessageBody.ImageBody();
        imageBody.setType(message.getType());
        if (message.getImageBody() != null) {
            imageBody.setMedia_id(message.getImageBody().getMedia_id());
        }
        return imageBody;


    }

    /**
     * (å¤çlinkæ¶æ¯å¯¹è±¡)
     *
     * @param message
     * @return
     */
    private DTMessageBody.LinkBody dealLinkBody(DingMessageVO message) {
        DTMessageBody.LinkBody linkBody = new DTMessageBody.LinkBody();
        linkBody.setType(message.getType());
        linkBody.setTitle(message.getLinkBody().getTitle());
        linkBody.setText(message.getLinkBody().getText());
        linkBody.setPicUrl(message.getLinkBody().getPicUrl());
        linkBody.setMessageUrl(message.getLinkBody().getMessageUrl());
        return linkBody;
    }

    /**
     * (å¤çtextæ¶æ¯å¯¹è±¡)
     *
     * @param message
     * @return
     */
    private DTMessageBody.TextBody dealTextBody(DingMessageVO message) {
        DTMessageBody.TextBody textBody = new DTMessageBody.TextBody();
        textBody.setType(message.getType());
        if (message.getTextBody() != null) {
            textBody.setContent(message.getTextBody().getContent());
        }
        return textBody;
    }

    /**
     * (å¤çoaæ¶æ¯å¯¹è±¡)
     *
     * @param message
     * @return
     */
    private DTMessageBody.OABody dealOABody(DingMessageVO message) {
        DTMessageBody.OABody oABody = new DTMessageBody.OABody();
        oABody.setType(message.getType());
        if (message.getoABody() == null) {
            return oABody;
        }
        DTMessageBody.OABody.Body b = new DTMessageBody.OABody.Body();
        b.setTitle(message.getoABody().getBodyTitle());
        b.setContent(message.getoABody().getBodyContent());
        if (!CollectionUtils.isEmpty(message.getoABody().getBodyFormMap())) {
            List<DTMessageBody.OABody.Body.Form> formList = new ArrayList<DTMessageBody.OABody.Body.Form>();
            message.getoABody().getBodyFormMap().forEach((k, v) -> {
                DTMessageBody.OABody.Body.Form f = new DTMessageBody.OABody.Body.Form();
                f.setKey(k);
                f.setValue(v);
                formList.add(f);
            });
            b.setForm(formList);
        }
        DTMessageBody.OABody.Head h = new DTMessageBody.OABody.Head();
        h.setBgcolor("FF87CEFA");
        oABody.setHead(h);
        try {
            oABody.setMessage_url("dingtalk://dingtalkclient/page/link?url=" + URLEncoder.encode(message.getoABody().getMsgUrl(), "UTF-8"));
        } catch (UnsupportedEncodingException ignore) {
        }
        oABody.setBody(b);
        return oABody;
    }

    /**
     * (校验参数)
     *
     * @param dingMessageVO
     */
    private void checkParam(DingMessageVO dingMessageVO) {
        checkArgument(Strings.isNullOrEmpty(dingMessageVO.getAccountType()), ExceptionCodeEnum.PARAM_ERROR.code(), "AccountTypeä¸è½ä¸ºç©º");
        checkArgument(Strings.isNullOrEmpty(dingMessageVO.getReceiverGid()), ExceptionCodeEnum.PARAM_ERROR.code(), "æ¥åèå¬å¸ç¼å·ReceiverGidä¸è½ä¸ºç©º");
//checkArgument(Strings.isNullOrEmpty(dingMessageVO.getSenderNo()), ExceptionCodeEnum.PARAM_ERROR.code(), "åéèå·¥å·SenderNoä¸è½ä¸ºç©º");
        checkArgument(CollectionUtils.isEmpty(dingMessageVO.getReceivers()) || dingMessageVO.getReceivers().size() > 500, ExceptionCodeEnum.PARAM_ERROR.code(), "æ¥åèReceiversä¸è½ä¸ºç©ºå¹¶ä¸ä¸è½å¤§äº500äºº");
    }
}